#! /bin/bash

# # # # # # # # # # # # # # # # # # # # # # 
# @file    :common_function.sh
# @author  :ying.hou
# @revision:2016-02-17 11:18:04
# # # # # # # # # # # # # # # # # # # # # # 

if [ -f ~/.bash_profile ] ; then
  source ~/.bash_profile
else
  if [ -f ~/.bashrc ] ; then
    source ~/.bashrc
  fi
fi

# 字符串字面值替换函数
# $1原始字符串
# $2匹配字符串
# $3替换字符串
str_replace() {
	echo "${1//${2}/${3}}"
}

# 计算两个时间点相差的秒数
# $1 时间点A
# $2 时间点B
abs_sub_seconds(){
  local SUB_SECONDS=$(($(date -d "$1" +'%s') - $(date -d "$2" +'%s')))
  if [ ${SUB_SECONDS} -ge 0 ] ; then
    echo ${SUB_SECONDS}
  else
    echo $((0 - ${SUB_SECONDS}))
  fi
}

# 检查进程是否存活
# $1 PID
check_process(){
  _CHECK_PROCESS_MSG_="$(ps -p $1 2>&1)"
  echo $?
}

# 发送邮件
# $1 发件人
# $2 收件人，逗号间隔
# $3 标题
# $4 正文
send_mail(){
  # 初始化参数
  local MAIL_FROM=$1
  local MAIL_MEMBERS=$2
  local MAIL_TITLE=$3
  local MAIL_BODY=$4

  # 组装内容
  local MAIL_MSG="$(echo "
    From:${MAIL_FROM}
    To:${MAIL_MEMBERS}
    Subject:${MAIL_TITLE}
    Content-Type: text/html; charset=utf-8
    <!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//ENhttp://www.w3.org/TR/html4/loose.dtd>
    <html>
      <head><meta http-equiv=Content-Type content=text/html; charset=utf-8 pageEncoding=UTF-8></head>
      <body>${MAIL_BODY}</body>
    </html>
  " | head -n-1 | tail -n+2 | sed -r 's/^[\t ]+//g')"

  # 发送邮件
  /usr/sbin/sendmail -t <<< "${MAIL_MSG}"
}

# 获取数字
get_number(){
  awk '$0 ~ /^-?([1-9][0-9]+|[0-9])$/ && NR==1{print}'
}

# 转换为邮件附件
# $1 MIME分隔符(boundary)
# $2-n 文件路径
convert_to_mail_attach(){
  # 参数校验
  if [ $# -lt 2 ] ; then
    print_msg "[${FUNCNAME} ${LINENO}] 函数[${FUNCNAME}]期待至少2个参数 MIME分隔符(boundary) 文件路径 [文件路径2] [文件路径3] [...]"
    return 1
  fi
  local MIME_BOUNDARY="$1"
  shift
  while [ $# -gt 0 ] ; do
    local ATTACHMENT_NAME="$(basename "$1" | base64)"
    echo ""
    echo "--${MIME_BOUNDARY}"
    echo "Content-Type: application/octet-stream;name=\"=?utf-8?B?${ATTACHMENT_NAME}?=\""
    echo "Content-Description:=?utf-8?B?${ATTACHMENT_NAME}?="
    echo "Content-Disposition: attachment; filename=\"=?utf-8?B?${ATTACHMENT_NAME}?=\"; size=$(du -b "$1" | awk '{print $1}')"
    echo "Content-Transfer-Encoding: base64"
    echo ""
    base64 "$1"
    shift
  done
}

# 获取正在执行的任务数
# $1 匹配字符串
get_process_num_by(){
  # 过滤掉多级调用的父进程,仅计算最终子进程数
  grep -P "$1" <<< "$(ps -AF)" | awk 'BEGIN{cnt=0;}{PID[$2]=1;PPID[$3]=1;}END{for(x in PID){if(!(x in PPID)){cnt += 1}};print cnt;}'
}

# 删除命令中的特殊字符
# $1 原始命令
trim_command(){
  tr -cd "[a-zA-Z0-9_./'\"]-" <<< $1
}

# $1 msg
function log_info() {
    local datetime=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$datetime][INFO][${BASH_SOURCE[1]}:$LINENO][${FUNCNAME[1]}] $1"
}

# $1 msg
function log_error() {
    local datetime=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$datetime][ERROR][${BASH_SOURCE[1]}:$LINENO][${FUNCNAME[1]}] $1"
}

# $1 JSON_STRING
# $2 JSON_PATH
function get_json_object() {
  local JSON_STRING="$1"
  local JSON_PATH="$2"
  local JSON_VALUE="$(jq "$JSON_PATH" <<< "$JSON_STRING")"
  echo "$JSON_VALUE" | sed 's/^"\(.*\)"$/\1/g'
}